<template>
  <el-drawer
    v-model="visible"
    title="复购单审核"
    size="900px"
    :close-on-click-modal="false"
    class="finance-review-drawer"
  >
    <div class="drawer-body" ref="drawerBodyRef">
      <!-- 基础信息 -->
      <el-descriptions :column="2" border class="mb-4">
        <el-descriptions-item label="客户姓名">{{ form.receiverName }}</el-descriptions-item>
        <el-descriptions-item label="客户电话">{{ form.receiverPhone }}</el-descriptions-item>
        <el-descriptions-item label="收货地址" :span="2">{{
          form.receiverAddress
        }}</el-descriptions-item>
        <el-descriptions-item label="订单来源">{{ form.channelType }}</el-descriptions-item>
        <el-descriptions-item label="订单时间">{{ form.orderTime }}</el-descriptions-item>
        <el-descriptions-item label="订单备注" :span="2">{{
          form.orderRemark || '无'
        }}</el-descriptions-item>
        <el-descriptions-item label="附件">
          <ImagePreview
            v-if="form?.fileAttachment"
            :src="form?.fileAttachment"
            width="120px"
            height="120px"
          />
          <div v-else style="color: #999">无附件</div>
        </el-descriptions-item>
      </el-descriptions>
      <!-- 包裹信息 -->
      <div
        v-for="(pkg, index) in form.childrens"
        :key="pkg.id"
        style="margin-top: 10px"
        class="package-card"
      >
        <el-card shadow="never" class="mb-4">
          <template #header>
            <div class="package-header">
              <span class="title">📦 包裹 {{ index + 1 }}</span>
              <el-button text size="small" @click="pkg.expanded = !pkg.expanded">
                <el-icon>
                  <component :is="pkg.expanded ? ArrowUp : ArrowDown" />
                </el-icon>
                {{ pkg.expanded ? '收起' : '展开' }}
              </el-button>
            </div>
          </template>
          <div v-if="pkg.expanded">
            <el-table :data="pkg.productCollection" :border="true" size="small">
              <el-table-column label="产品名称" prop="productName" />
              <el-table-column
                label="产品类型"
                prop="usageType"
                width="110"
                :formatter="getGoodsTypeByUsageType"
              >
              </el-table-column>
              <el-table-column label="件数" prop="usageType"> </el-table-column>
              <!-- <el-table-column label="成本价" width="80" prop="costPrice" />
            <el-table-column label="销售价" width="150" prop="salePrice" /> -->
            </el-table>

            <div class="total-bar">
              <span
                >合计：<b>{{ calcPkgQty(pkg) }}</b> 件 &nbsp;
                <b class="amount">{{ pkg.totalAmount }}</b>
                元</span
              >
            </div>
          </div>
          <!-- 折叠预览 -->
          <div v-if="!pkg.expanded" class="pkg-preview">
            {{ getProduct(pkg.productCollection, pkg.totalAmount) }}
          </div>
        </el-card>
      </div>

      <!-- 付款信息 -->
      <div class="section-title">付款信息</div>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="付款方式">{{ form.paymentMethod }}</el-descriptions-item>
        <el-descriptions-item label="总金额">{{ form.totalAmount }}</el-descriptions-item>
        <el-descriptions-item label="已付金额">{{ form.actualPrice }}</el-descriptions-item>
        <el-descriptions-item label="代收金额">{{ form.codAmount }}</el-descriptions-item>
        <el-descriptions-item label="是否大单">{{
          form.isBigOrder ? '是' : '否'
        }}</el-descriptions-item>
        <el-descriptions-item label="延期发货">
          {{ form.isDelayedDelivery ? '是' : '否' }}
        </el-descriptions-item>
        <el-descriptions-item label="物流公司">{{ form.logisticsPlatform }}</el-descriptions-item>
        <el-descriptions-item label="物流单号">{{ form.logisticsNo }}</el-descriptions-item>
      </el-descriptions>

      <!-- 审核备注 -->
      <div class="section-title">审核备注</div>
      <el-input v-model="auditRemark" type="textarea" rows="3" placeholder="请输入审核备注" />
    </div>

    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <!-- <el-button type="danger" @click="reject">驳回</el-button> -->
      <el-button type="primary" :loading="submitLoading" @click="approve">核销</el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { ref, reactive, watch, toRaw, computed } from 'vue';
import { ArrowUp, ArrowDown, User, Phone, Van } from '@element-plus/icons-vue';
import { cloneDeep } from 'lodash';
import { dayjs, ElMessage } from 'element-plus';
import { verificationOrder } from '../../api/platformOrders/orders/list';

const props = defineProps({
  goodsList: {
    type: Array,
    default: () => []
  },
  goodsTypes: {
    type: Array,
    default: () => []
  }
});

const emits = defineEmits(['ok']);
const visible = ref(false);
const auditRemark = ref('');
const drawerBodyRef = ref();

// 包裹信息
const initPkgItem = () => ({
  id: Date.now(),
  expanded: true,
  productCollection: cloneDeep(toRaw(props.goodsList)),
  actualPrice: 0,
  codAmount: 0,
  totalAmount: 0
});

// 初始化表单数据
const initField = () => ({
  orderId: null,
  // 客户信息
  recognizeText: '',
  receiverName: '',
  receiverPhone: '',
  receiverAddress: '',
  // 订单信息
  paymentMethod: '',
  isBigOrder: 0,
  actualPrice: 0,
  codAmount: 0,
  totalAmount: 0,
  orderRemark: '',
  channelType: '',
  fileAttachment: '',
  // 物流类型
  shippingType: '1',
  orderTime: '',
  isDelayedDelivery: 0,
  logisticsPlatformCode: '',
  expressNo: '',
  packages: [initPkgItem()] as any
});

// 表单数据
const form = reactive<any>({});

watch(
  () => props.goodsList,
  () => {
    // 初始化表单数据
    const newField = initField();
    // 初始化商品列表
    for (const key in newField) {
      form[key] = newField[key];
    }
  },
  {
    immediate: true
  }
);

// 根据产品类型
const getGoodsTypeByUsageType = (row: any) => {
  const type = row.usageType;
  const findx: any = props.goodsTypes.filter((item: any) => item.value == type);
  if (findx.length > 0) {
    return findx[0].label;
  }
  return '';
};

// 获取商品名称 和 数量
const getProduct = (pkg: any, totalAmount: number) => {
  let productName = '';
  let productNum = 0;
  pkg.forEach((item: any) => {
    productName +=
      item.productName + ' - ' + getGoodsTypeByUsageType(item) + ' x ' + item.num + '，';
    productNum += item.num;
  });
  return productName + '共' + productNum + '件，金额' + totalAmount + '元';
};

// 计算包裹药品数量
const calcPkgQty = (pkg: any) => pkg.productCollection.reduce((sum, p) => sum + p.num, 0);

const submitLoading = ref(false);

const show = (data) => {
  // 将data 替换掉 form form 是 reactive 不能直接赋值
  Object.assign(form, data);
  visible.value = true;
};

const approve = () => {
  // 校验
  if (!auditRemark.value) {
    ElMessage.error('请输入审核备注');
    return;
  }

  verificationOrder({
    orderId: form.orderId,
    verRemark: auditRemark.value
  })
    .then((res) => {
      submitLoading.value = false;
      if (res.code == 200) {
        ElMessage.success('核销成功');
        emits('ok');
        hide();
      }
    })
    .catch(() => {
      submitLoading.value = false;
    });
};

const hide = () => {
  visible.value = false;
  auditRemark.value = '';
};

defineExpose({ show, hide });
</script>

<style scoped lang="scss">
.finance-review-drawer {
  .drawer-body {
    height: 100%;
    overflow-y: auto;
    padding: 0 8px 20px 8px;
  }

  .package-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 16px;
    font-weight: 600;
    color: #409eff;
  }

  .section-title {
    margin: 16px 0 8px;
    font-weight: 600;
    font-size: 15px;
    color: #333;
  }

  .total-bar {
    text-align: right;
    margin: 8px 0;
    font-size: 14px;
    font-weight: 500;
    color: #333;

    .amount {
      color: #f56c6c;
      font-weight: 700;
    }
  }

  .attachments {
    display: flex;
    flex-wrap: wrap;
  }

  .remark-text {
    background: #f9fafb;
    border: 1px solid #ebeef5;
    border-radius: 6px;
    padding: 8px 12px;
    color: #606266;
    font-size: 14px;
  }

  .pkg-preview {
    display: flex;
    align-items: center;
    gap: 12px;
    font-size: 14px;
    color: #606266;
    background: #f9fafb;
    padding: 8px 12px;
    border-radius: 8px;
    border: 1px solid #ebeef5;
    transition: all 0.2s ease;

    .pkg-field {
      display: flex;
      align-items: center;
      gap: 4px;
      font-weight: 500;
      color: #303133;

      svg {
        font-size: 16px;
        color: #909399;
      }
    }

    .separator {
      color: #dcdfe6;
    }
  }
}
</style>
